package com.party.web.web.controller.system;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityWithMemberPartner;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleType;
import com.party.core.model.material.MaterialMember;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.TargetType;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.member.IMemberGroupPermissionService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.biz.system.member.MemberGroupPermissionBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.system.GroupPermissionInput;
import com.party.web.web.dto.input.system.MaterialInput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Nullable;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MemberGroupPermissionController
 * @Description 机构数据权限
 * @Author yifeng
 * @Date 2019/11/26 11:14
 **/
@Controller
@RequestMapping(value = "memberGroup/Permission")
public class MemberGroupPermissionController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemberGroupPermissionBizService memberGroupPermissionBizService;

    @Autowired
    private IMemberGroupPermissionService memberGroupPermissionService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ISysRoleService sysRoleService;


    @ResponseBody
    @RequestMapping(value = "save")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(@Validated GroupPermissionInput permissionInput, BindingResult result) {
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(description);
        }
        try {
            memberGroupPermissionBizService.save(permissionInput);
            return AjaxResult.success();
        } catch (BusinessException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("保存机构数据权限异常", e);
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("保存机构数据权限异常", e);
            return AjaxResult.error("保存机构数据权限异常");
        }
    }

    @RequestMapping(value = "toSetPermission")
    public ModelAndView toSetPermission(String memberId, String partnerId) {
        ModelAndView mv = new ModelAndView();
        Integer isShowAll = 0;

/*        boolean resutle = sysRoleService.hasRole(memberId, RoleEnum.BRANCH_DIRECTOR.getCode());
        if (resutle) {
            mv.setViewName("system/memberGroup/setGroupPermissionMaterial");
            isShowAll = memberGroupPermissionService.getIsShowAll(TargetType.MATERIAL.getCode(), memberId, partnerId, Lists.newArrayList());
        } else {*/
            mv.setViewName("system/memberGroup/setGroupPermission");
            isShowAll = memberGroupPermissionService.getIsShowAll(TargetType.ACTIVITY.getCode(), memberId, partnerId, Lists.newArrayList());
/*        }*/

        mv.addObject("memberId", memberId);
        mv.addObject("partnerId", partnerId);
        mv.addObject("isShowAll", isShowAll);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "dataList")
    public AjaxResult dataList(String memberId, String partnerId, String type) {
        try {
            List<Map<String, String>> mapList = Lists.newArrayList();
            List<String> targetIds = Lists.newArrayList();
            Integer isShowAll = memberGroupPermissionService.getIsShowAll(type, memberId, partnerId, targetIds);
            if (null != isShowAll && YesNoStatus.NO.getCode().equals(isShowAll)) {
                if (TargetType.ACTIVITY.getCode().equals(type)) { //活动
                    List<Activity> activities = activityService.batchList(new HashSet<>(targetIds), new Activity(), null);
                    mapList = LangUtils.transform(activities, new Function<Activity, Map<String, String>>() {
                        @Nullable
                        @Override
                        public Map<String, String> apply(@Nullable Activity input) {
                            Map<String, String> map = Maps.newHashMap();
                            map.put("id", input.getId());
                            map.put("title", input.getTitle());
                            return map;
                        }
                    });
                } else if (TargetType.MATERIAL.getCode().equals(type)) { //素材
                    List<Article> articles = articleService.batchList(new HashSet<>(targetIds), new Article(), null);
                    mapList = LangUtils.transform(articles, new Function<Article, Map<String, String>>() {
                        @Nullable
                        @Override
                        public Map<String, String> apply(@Nullable Article input) {
                            Map<String, String> map = Maps.newHashMap();
                            map.put("id", input.getId());
                            map.put("title", input.getTitle());
                            return map;
                        }
                    });
                }
            }
            return AjaxResult.success(mapList);
        } catch (Exception e) {
            logger.error("获取已分配的数据异常", e);
            return AjaxResult.error("获取已分配的数据异常");
        }
    }

    @RequestMapping(value = "selectMaterial")
    public ModelAndView selectMaterial(MaterialInput input, Page page) {
        ModelAndView mv = new ModelAndView("member/material/selectMaterial");
        Map<String, Object> params = Maps.newHashMap();
        params.put("title", input.getTitle());
        params.put("member", input.getMember());
        params.put("articleType", ArticleType.ARTICLE_TYPE_MATERIAL.getCode());
        List<Article> articles = articleService.queryArticleList(params, page);
        mv.addObject("articles", articles);
        mv.addObject("page", page);
        mv.addObject("input", input);
        return mv;
    }
}
